package com.niudong.esdemo.service.impl;

import com.niudong.esdemo.service.SearchService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class SearchServiceImpl2 implements SearchService {

    private static Log log = LogFactory.getLog(SearchServiceImpl.class);
    private RestHighLevelClient restClient;

    @PostConstruct
    public void initEs() {
        restClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        log.info("es start");
    }


    public void closeEs(){
        try {
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void  buildSearchRequest(){
        SearchRequest searchRequest = new SearchRequest();

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);

        searchRequest = new SearchRequest("posts");

        searchRequest.routing("routing");

        /**
         * Controls how to deal with unavailable concrete indices (closed or missing),
         * how wildcard expressions are expanded to actual indices (all, closed or open indices)
         * and how to deal with wildcard expressions that resolve to no indices.
         */
        searchRequest.indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN);


        searchRequest.preference("_local");


        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        sourceBuilder.query(QueryBuilders.termQuery("content","货币"));

        sourceBuilder.from(0);
        sourceBuilder.size(5);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        searchRequest.source(sourceBuilder);

        //matchquerybuilder

        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("content", "货币");

        matchQueryBuilder.fuzziness(Fuzziness.AUTO);

        matchQueryBuilder.prefixLength(3);
        matchQueryBuilder.maxExpansions(10);

        //流式编程
        matchQueryBuilder = QueryBuilders.matchQuery("content", "货币").fuzziness(Fuzziness.AUTO).prefixLength(3).maxExpansions(10);


        searchSourceBuilder.query(matchQueryBuilder);


        /**
         * 指定排序方法的使用
         */
        sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));

        sourceBuilder.sort(new FieldSortBuilder("_id").order(SortOrder.ASC));


        sourceBuilder.fetchSource(false);

        java.lang.String[] includeFields = new java.lang.String[] {"title", "innerObject.*"};
        java.lang.String[] excludeFields = new java.lang.String[] {"user"};

        sourceBuilder.fetchSource(includeFields,excludeFields);


        HighlightBuilder highlightBuilder = new HighlightBuilder();


        highlightBuilder.highlighterType("unified");
        highlightBuilder.field("");

        // 添加第二个高亮显示字段
        HighlightBuilder.Field highlightUser = new HighlightBuilder.Field("user");
        highlightBuilder.field(highlightUser);

        searchSourceBuilder.highlighter(highlightBuilder);


        TermsAggregationBuilder aggregation = AggregationBuilders.terms("by_company").field("company.keyword");

        aggregation.subAggregation(AggregationBuilders.avg("average_age").field("age"));
        searchSourceBuilder.aggregation(aggregation);


        TermSuggestionBuilder termSuggestionBuilder = SuggestBuilders.termSuggestion("content").text("货币");

        SuggestBuilder suggestBuilder = new SuggestBuilder();

        suggestBuilder.addSuggestion("suggest_user",termSuggestionBuilder);
        searchSourceBuilder.suggest(suggestBuilder);

        searchSourceBuilder.profile(true);


    }

    @Override
    public void executeSearchRequest() {

    }
}
